package com.byx.chatserver.service.impl;

import com.byx.chatserver.entity.MailType;
import com.byx.chatserver.pojo.RedisKeyDto;
import com.byx.chatserver.service.IMailService;
import com.byx.chatserver.service.IRedisService;
import com.byx.chatserver.service.IVerificationCodeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

/**
 * EmailVerificationCodeServiceImpl
 * 发送邮件验证码
 * @author Superb
 * @date 2021/3/22 22:29
 */
@Service
public class EmailVerificationCodeServiceImpl implements IVerificationCodeService {
    /**
     *  验证码过期时间
     */
    private static final int EXPIRATION_TIME = 300;
    /**
     *  验证码长度
     */
    public static final int CODE_LENGTH = 6;
    /**
     *  标题
     */
    public static final String SUBJECT = "验证码邮件";

    @Resource
    private IRedisService redisService;

    @Resource
    private IMailService mailService;

    @Override
    public boolean sendVerificationCode(String number, MailType mailType) {
        boolean result = false;
        String code = getRandNum(CODE_LENGTH);
        try {
            mailService.send(number,SUBJECT,code,mailType);
            result = true;

            RedisKeyDto redisKeyDto = new RedisKeyDto();
            redisKeyDto.setKey(number);
            redisKeyDto.setValue(code);
            redisService.addRedisData(redisKeyDto,EXPIRATION_TIME);
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public boolean isCorrectCode(String number, String code) {
        RedisKeyDto redisKeyDto = new RedisKeyDto();
        redisKeyDto.setKey(number);
        RedisKeyDto result = redisService.redisGet(redisKeyDto);
        if (result != null && result.getValue().equals(code)){
            redisService.delete(redisKeyDto);
            return true;
        }
        return false;
    }

    @Override
    public String getRandNum(int length) {
        StringBuilder charValue = new StringBuilder();
        for (int i = 0; i < length; i++) {
            Random random = new Random();
            char c = (char) (random.nextInt(10) + '0');
            charValue.append(c);
        }
        return charValue.toString();
    }
}
